package com.nineclock.common.filter;

import cn.hutool.core.util.StrUtil;
import com.nineclock.common.entity.UserInfo;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import com.nineclock.common.utils.JsonUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter(filterName = "currentUserFilter", urlPatterns = "/*")
public class CurrentUserFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            // 获取当前登录用户信息
            String name = SecurityContextHolder.getContext().getAuthentication().getName();

            //判定, 转换成实体类 UserInfo
            if(StrUtil.isNotEmpty(name) && !"anonymousUser".equals(name)){
                UserInfo userInfo = JsonUtils.toBean(name, UserInfo.class);
                //存放到ThreadLocal中
                CurrentUserHolder.set(userInfo);
            }

            //放行请求, 执行原始请求
            chain.doFilter(request, response);
        } finally {

            CurrentUserHolder.remove();//释放内存
        }

    }

}
